<?php

namespace App\Admin\Models;

use App\Common\Models\Region;
use App\Common\Services\Admin\Common as AdminCommon;
use App\Common\Services\Common;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SiteCompany extends Model
{
    protected $table = 'site_company_list';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     *获取列表 
     */
    public static function getList(Request $request)
    {
        
        $info=AdminCommon::getCurrentAdmininfo($request);
        if($info['type']!=1){//运维只可查看自己
            $query = self::where(['admin_user_id'=>$info['id']])->orderBy('create_at', 'desc');
        }else{
            $query = self::orderBy('create_at', 'desc');
        }
        $query=$query->with(['adminuserinfo',
        // 'pcodeinfo','ccodeinfo','dcodeinfo'
    ])->where('is_del',1);
        

        $audit_status = $request->audit_status ?? 0;
        $isgetall = intval($request->isgetall) ?? 0;
        if (in_array($audit_status, [1, 2, 3, 4])) {
            $query->where('audit_status', $audit_status);
        }
        $company_name = $request->company_name;
        if ($company_name != '') {
            $query->where('company_name', 'like', '%' . $company_name . '%');
        }

        $contact_phone = $request->contact_phone;
        if ($contact_phone != '') {
            $query->where('contact_phone', 'like', '%' . $contact_phone . '%');
        }

        $withoutcpid = intval($request->withoutcpid);//排除指定公司
        if ($withoutcpid>0) {
            $query->where('id', '<>',$withoutcpid);
        }


        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    public function adminuserinfo(){
        return $this->hasOne(AdminUser::class, 'id', 'admin_user_id');
    }

    public function pcodeinfo(){
        return $this->hasOne(Region::class, 'code', 'p_code');
    }
    public function ccodeinfo(){
        return $this->hasOne(Region::class, 'code', 'c_code');
    }
    public function dcodeinfo(){
        return $this->hasOne(Region::class, 'code', 'd_code');
    }
}
